package cn.tedu.egmvc2.base.exception;

import cn.tedu.egmvc2.base.response.JsonResult;
import cn.tedu.egmvc2.base.response.StateCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.validation.UnexpectedTypeException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String data = e.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:"+data);
        return new JsonResult(StateCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e){
        String data = e.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:"+data);
        return new JsonResult(StateCode.VALIDATED_ERROR,data);
    }
}
